<template>
  <div class="q-pa-none" style="height: 100%; width: 100%; overflow: auto">
    <q-btn dense label="postMessage" flat @click="post" />
    <!--拖拽框菜单-->
    <div id="drag-context-menu">
      <q-card class="q-py-xs bg-purple">
        <q-item>
          <q-btn class="full-width" dense>拖拽框菜单</q-btn>
        </q-item>
      </q-card>
    </div>
    <!--窗口菜单-->
    <div id="win-context-menu">
      <q-card class="q-pa-xs bg-white">
        <q-btn>添加元素</q-btn>
      </q-card>
    </div>

    <Vue3DraggableResizable
      class-name-active="active-class"
      v-for="(item, index) in dbList"
      :id="'test' + index"
      :key="index"
      :debug="false"
      :h="item.h"
      :resizable="false"
      :w="item.w"
      :x="item.x"
      :y="item.y"
      class="dragDiv overflow-hidden"
      @dragging="onDrag"
      @resizing="(e) => onResize(e, index)"
      @contextmenu="clickDb()"
    >
      <!--      @contextmenu.prevent="showDragContextMenu"-->
      <q-card
        bordered
        class="q-pa-none"
        class-name-active="glass-2"
        flat
        style="height: 100%; width: 100%; z-index: 1"
      >
        <q-table
          v-model:pagination="pagination"
          :columns="item.col"
          :rows="item.row"
          :rows-per-page-options="[0]"
          :style="{
            height: item.h + 'px',
            width: item.w + 'px',
          }"
          :visible-columns="visibleColumns"
          class="my-sticky-dynamic"
          dense
          flat
          no-data-label="无数据"
          row-key="name"
          separator="cell"
          style="max-height: 400px; max-width: 600px; min-width: 300px"
          virtual-scroll
        >
          <template v-slot:top>
            <div class="flex row justify-center no-wrap items-center">
              <div class="q-mr-lg">
                {{ item.table.TABLE_NAME + item.table.TABLE_COMMENT }}
              </div>
              <q-select
                v-model="visibleColumns"
                display-value="显示列"
                :options="item.col"
                dense
                emit-value
                map-options
                multiple
                option-value="name"
                options-cover
                options-dense
                outlined
                style="min-width: 90px"
              />
            </div>
          </template>
          <template v-slot:body="props">
            <q-tr :props="props">
              <q-td
                v-for="item in props.cols"
                class="bg-amber-1 dragItem"
                :key="item.name"
                :props="props"
              >
                <!--                      <q-input dense borderless v-model="props.row[item.name]"/>-->
                {{ props.row[item.name] }}
                <q-popup-edit
                  v-slot="scope"
                  v-model="props.row[item.name]"
                  :title="item.name"
                  buttons
                >
                  <q-input v-model="scope.value" autofocus dense outlined />
                </q-popup-edit>
              </q-td>
            </q-tr>
          </template>
        </q-table>
      </q-card>
    </Vue3DraggableResizable>

    <q-dialog v-model="genCodeShow" maximized>
      <q-stepper
        class="z-index-3"
        v-model="step"
        header-nav
        ref="stepper"
        color="primary"
        animated
      >
        <q-step :name="1" title="选择主表" icon="settings" :done="done1">
          <q-btn
            @click="dbSelected.push({ col: [], db: '' })"
            color="accent"
            label="添加主表"
            class="q-mb-lg text-bold"
          />
          <div
            class="flex q-gutter-x-xs q-my-xs no-wrap"
            v-for="(i, index) in dbSelected"
            :key="index"
          >
            <q-select
              dense
              label="表"
              standout
              v-model="i.db"
              :options="dbTreeList"
              option-label="TABLE_NAME"
              emit-value
              map-options
              style="min-width: 150px; max-width: 300px"
            />
            <q-select
              dense
              label="字段"
              standout
              v-model="i.col"
              :options="colList"
              option-label="COLUMN_NAME"
              emit-value
              multiple
              map-options
              style="min-width: 500px; width: 700px"
            >
              <template v-if="i.col.length" v-slot:append>
                <q-icon
                  name="cancel"
                  @click.stop.prevent="i.col = []"
                  class="cursor-pointer"
                />
              </template>
            </q-select>
          </div>
          <q-stepper-navigation>
            <q-btn
              @click="
                () => {
                  done1 = true;
                  step = 2;
                }
              "
              color="primary"
              class="text-bold"
              label="下一步"
            />
          </q-stepper-navigation>
        </q-step>

        <q-step
          :name="2"
          title="选择附表"
          caption="Optional"
          icon="create_new_folder"
          :done="done2"
        >
          <q-btn
            @click="joinSelected.push({ col: [], db: '', key: '', value: '' })"
            color="accent"
            label="添加附表"
            class="q-mb-lg text-bold"
          />
          <div
            class="flex q-gutter-x-xs q-my-xs no-wrap"
            v-for="(i, index) in joinSelected"
            :key="index"
          >
            <q-select
              dense
              label="表"
              standout
              v-model="i.db"
              :options="dbTreeList"
              option-label="TABLE_NAME"
              emit-value
              map-options
              style="min-width: 150px; max-width: 300px"
            />
            <q-select
              dense
              label="字段"
              standout
              v-model="i.col"
              :options="colList"
              option-label="COLUMN_NAME"
              emit-value
              multiple
              map-options
              style="min-width: 300px; width: 400px"
            />
            <q-select
              dense
              label="对应附字段"
              standout
              v-model="i.value"
              :options="colList"
              option-label="COLUMN_NAME"
              emit-value
              map-options
              style="min-width: 150px; width: 400px"
            >
            </q-select>
            <q-select
              color="orange"
              style="min-width: 160px; width: 300px"
              dense
              label="对应主字段"
              standout
              v-model="i.key"
              :options="keyList"
            >
              <template v-if="i.key" v-slot:append>
                <q-icon
                  name="cancel"
                  @click.stop.prevent="i.key = null"
                  class="cursor-pointer"
                />
              </template>
            </q-select>
          </div>

          <q-stepper-navigation>
            <q-btn
              @click="gotoStep3"
              color="primary"
              label="下一步"
              class="text-bold"
            />
            <q-btn
              flat
              @click="step = 1"
              color="primary"
              label="上一步"
              class="q-ml-sm text-bold"
            />
          </q-stepper-navigation>
        </q-step>

        <q-step :name="3" title="生成语句" icon="add_comment" :done="done3">
          <q-splitter
            v-model="splitterModel"
            horizontal
            style="height: calc(100vh - 170px)"
          >
            <template v-slot:before>
              <!--              <div-->
              <!--                  class="q-py-xs q-px-xs glass-10 full-height overflow-auto define-scroll rounded-borders"-->
              <!--              >-->
              <!--                <q-btn-->
              <!--                    v-for="i in mineTemplateList"-->
              <!--                    :key="i"-->
              <!--                    class=" rounded-borders flex q-px-md q-mb-xs no-wrap full-width"-->
              <!--                    :class="-->
              <!--                      i.templateId == templateId-->
              <!--                        ? 'bg-gradation-to-top-9890e3-b1f4cf'-->
              <!--                        : ''-->
              <!--                    "-->
              <!--                    dense-->
              <!--                    @click="updateEditor(i.templateId)"-->
              <!--                >-->
              <!--                  {{ i.name }}-->
              <!--                  No:{{ i.templateId }}-->
              <!--                </q-btn>-->
              <!--              </div>-->
              <div style="width: 100%; height: 100%">
                <div class="flex items-center q-px-lg q-mb-xs">
                  模板内容：
                  <q-select  style="width: 250px;"
                    emit-value
                    v-model="templateId"
                    :options="mineTemplateList"
                    option-label="name"
                    option-value="templateId"
                    map-options
                    filled
                    dense
                  />
                </div>
                <q-card
                  bordered
                  class="bg-transparent"
                  flat
                  style="height: calc(100% - 45px); width: calc(100% - 4px)"
                >
                  <!--            :on-chang-content="onTemplateContentChange"-->

                  <!--        :template-id="tab"-->
                  <ql-editor
                    ref="templateRef"
                    :on-chang-content="onTemplateContentChange"
                    :content="templateContent"
                    temp-type="java"
                    editor-id="templateEditor"
                  />
                </q-card>
              </div>
            </template>
            <template v-slot:after>
              <q-splitter v-model="bottomModel">
                <template v-slot:before>
                  <q-card
                    bordered
                    class="bg-transparent"
                    flat
                    style="height: 100%; width: calc(100% - 4px)"
                  >
                    <!--            :on-chang-content="onTemplateContentChange"-->
                    <!--        :template-id="tab"-->
                    <ql-editor
                      :on-chang-content="onDataContentChange"
                      :content="dataContent"
                      temp-type="yaml"
                      editor-id="dataEditor"
                    />
                  </q-card>
                </template>

                <template v-slot:after>
                  <q-card
                    bordered
                    class="bg-transparent"
                    flat
                    style="height: 100%; width: calc(100% - 4px)"
                  >
                    <!--            :on-chang-content="onTemplateContentChange"-->
                    <!--        :template-id="tab"-->
                    <ql-editor
                      :on-chang-content="onRenderContentChange"
                      temp-type="java"
                      :content="renderContent"
                      editor-id="renderEditor"
                    />
                  </q-card>
                </template>
              </q-splitter>
            </template>
          </q-splitter>

          <q-stepper-navigation class="q-pt-md">
            <q-btn
              dense
              color="primary"
              @click="done3 = true"
              label="关闭"
              class="text-bold"
            />
            <q-btn
              dense
              flat
              @click="step = 2"
              color="primary"
              label="返回"
              class="q-ml-sm text-bold"
            />
          </q-stepper-navigation>
        </q-step>
      </q-stepper>
    </q-dialog>
  </div>
</template>
<script lang="ts" setup>
import { nextTick, onMounted, ref, watch } from 'vue';
import QlEditor from 'components/QlEditor.vue';
import yaml                from 'js-yaml';
import { useGenStore }     from 'stores/genStore';
import { getMineTemplate } from 'src/api/api';

let cx: number, cy: number;
const step = ref(0);
const splitterModel = ref(30);
const bottomModel = ref(30);
const done1 = ref(false);
const done2 = ref(false);
const done3 = ref(false);
const dbSelected = ref([]);
const joinSelected = ref([]);
const colList = ref([]);
const keyList = ref([]);
const genCodeShow = ref(true);
const templateId = ref('');
const templateRef = ref(null);
const gotoStep3 = () => {
  done2.value = true;
  templateId.value = 10;
  step.value = 3;
};
const onDataContentChange = () => {
  console.log('onTemplateContentChange');
  refreshTemplateContent();
};
const dataContent = ref('');
const renderContent = ref('');
const templateContent = ref('');
const onRenderContentChange = () => {
  console.log('onTemplateContentChange');
};
const onTemplateContentChange = () => {
  console.log('onTemplateContentChange');
  refreshTemplateContent();
};
const refreshTemplateContent = () => {
  window.parent.postMessage(
    JSON.stringify({
      templateId: templateId.value,
      templateContent: templateRef.value?.getEditorContent(),
      data: yaml.load(dataContent.value),
    }),
    '*'
  );
};
const refreshTable = () => {
  window.parent.postMessage(
    JSON.stringify({
      data: 'table',
    }),
    '*'
  );
};
const refreshTemplateList = () => {
  getMineTemplate().then(async (res) => {
    mineTemplateList.value = res.data.data;
  });
};
watch(templateId, () => {
  console.log(mineTemplateList.value);
  dataContent.value = yaml.dump({
    db: dbSelected.value.map((i) => {
      return {
        db: {
          db: i.db.TABLE_NAME,
          db1: useGenStore().capitalizeFirstLetter(
            useGenStore().underscoreToCamelCase(i.db.TABLE_NAME)
          ),
          db2: useGenStore().underscoreToCamelCase(i.db.TABLE_NAME),
        },
        col: i.col.map((j) => {
          return {
            col: j.COLUMN_NAME,
            col1: useGenStore().capitalizeFirstLetter(
              useGenStore().underscoreToCamelCase(j.COLUMN_NAME)
            ),
            col2: useGenStore().underscoreToCamelCase(j.COLUMN_NAME),
          };
        }),
      };
    }),
    join: joinSelected.value.map((i) => {
      return {
        db: {
          db: i.db.TABLE_NAME,
          db1: useGenStore().capitalizeFirstLetter(
            useGenStore().underscoreToCamelCase(i.db.TABLE_NAME)
          ),
          db2: useGenStore().underscoreToCamelCase(i.db.TABLE_NAME),
        },
        col: i.col.map((j) => {
          return {
            col: j.COLUMN_NAME,
            col1: useGenStore().capitalizeFirstLetter(
              useGenStore().underscoreToCamelCase(j.COLUMN_NAME)
            ),
            col2: useGenStore().underscoreToCamelCase(j.COLUMN_NAME),
          };
        }),
      };
    }),
    key: joinSelected.value.map((j) => {
      console.log(j);
      return {
        key: j.key.split('.').map((i) => {
          return {
            key: i,
            key1: useGenStore().capitalizeFirstLetter(
              useGenStore().underscoreToCamelCase(i)
            ),
            key2: useGenStore().underscoreToCamelCase(i),
          };
        }),
        value: {
          value: j.value.COLUMN_NAME,
          value1: useGenStore().capitalizeFirstLetter(
            useGenStore().underscoreToCamelCase(j.value.COLUMN_NAME)
          ),
          value2: useGenStore().underscoreToCamelCase(j.value.COLUMN_NAME),
        },
      };
    }),
  });
  refreshTemplateContent();
});
watch(
  dbSelected,
  () => {
    dbSelected.value.forEach((i) => {
      colList.value = i.db.fields;
    });
    keyList.value = [];
    dbSelected.value.forEach((i) => {
      i.col.forEach((j) => {
        keyList.value.push(i.db.TABLE_NAME + '.' + j.COLUMN_NAME);
      });
    });
  },
  { deep: true }
);
watch(
  joinSelected,
  () => {
    joinSelected.value.forEach((i) => {
      colList.value = i.db.fields;
    });
  },
  { deep: true }
);
watch(
  joinSelected,
  () => {
    joinSelected.value.forEach((i) => {
      colList.value = i.db.fields;
    });
  },
  { deep: true }
);
const post = () => {
  window.parent.postMessage('Hello from iframe!', '*');
};
//防抖参数
const debounce = ref(true);
const visibleColumns = ref([
  'COLUMN_NAME',
  'COLUMN_DEFAULT',
  'COLUMN_TYPE',
  'COLUMN_KEY',
  'EXTRA',
  'COLUMN_COMMENT',
]);

watch(debounce, () => {
  if (!debounce.value)
    setTimeout(() => {
      debounce.value = true;
    }, 200);
});
watch(
  visibleColumns,
  () => {
    console.log(visibleColumns.value);
  },
  { deep: true }
);
const pagination = {
  rowsPerPage: 0,
};

const clickDb = async () => {
  let res = '';
  res = await window.ipcCom.dbMenu();
  console.log(res);
};
let line: any;
const dbTreeList = ref({} as { tables: object });
const mineTemplateList = ref([]);
const dbTree = ref([
  {
    label: 'xiu-life',
    name: 'xiu-life',
    icon: 'storage',
    children: [
      {
        name: 'tables',
        label: 'tables',
        data: 'tables',
        icon: 'folder',
        children: [],
      },
    ],
  },
]);
const dbList = ref(
  [] as {
    h: number;
    w: number;
    x: number;
    y: number;
    name: string;
    col: object;
    row: object;
  }[]
);
watch(
  dbList,
  () => {
    nextTick(() => {
      // initDrag();
    });
  },
  { deep: true }
);
let TableFieldMapper = {
  TABLE_CATALOG: '',
  TABLE_SCHEMA: '',
  TABLE_NAME: '',
  COLUMN_NAME: '名字',
  ORDINAL_POSITION: '',
  COLUMN_DEFAULT: '默认',
  IS_NULLABLE: '空',
  DATA_TYPE: '类型',
  CHARACTER_MAXIMUM_LENGTH: '',
  CHARACTER_OCTET_LENGTH: '',
  NUMERIC_PRECISION: '',
  NUMERIC_SCALE: '',
  DATETIME_PRECISION: '',
  CHARACTER_SET_NAME: '',
  COLLATION_NAME: '',
  COLUMN_TYPE: '类型',
  COLUMN_KEY: '键',
  EXTRA: '拓展',
  PRIVILEGES: '主键',
  COLUMN_COMMENT: '描述',
  GENERATION_EXPRESSION: '',
  SRS_ID: '',
};
onMounted(() => {
  refreshTable();
  refreshTemplateList();
  window.addEventListener('message', function (event) {
    let data = JSON.parse(event.data);
    console.log('data', data);
    console.log(data.type, data.data);
    switch (data.type) {
      case 'tables': {
        dbTreeList.value = data.data;
        console.log(Object.keys(dbTreeList.value[0].fields[0]));
        let deCol = [];
        Object.keys(dbTreeList.value[0].fields[0]).forEach((item) => {
          if (TableFieldMapper[item])
            deCol.push({
              name: item,
              label: TableFieldMapper[item],
              field: item,
              align: 'center',
              sortable: true,
            });
        });
        dbTreeList.value.forEach((i, index) => {
          dbList.value.push({
            table: i,
            col: deCol,
            row: i.fields,
            x: 650 * (index % 4),
            y: (450 * (index - (index % 4))) / 4,
          });
        });
        break;
      }
      case 'render': {
        console.log('render');
        renderContent.value = data.data.render;
        if (!templateContent.value) templateContent.value = data.data.content;
        break;
      }
    }
    if (data.type === 'tables') {
    }
  });
});

const onDrag = () => {
  // if (line) line.position();
};
const onResize = (e, index) => {
  console.log(e, index);
  // console.log((dragList.value[index] = e));
};
</script>
<style lang="sass">
html, body, #q-app
  height: 100%
  width: 100%
/* 设置滚动条的样式 */
::-webkit-scrollbar
  width: 4px
  height: 4px

/*滚动槽*/
::-webkit-scrollbar-track
  box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1)
  border-radius: 2px

/* 滚动条滑块 */
::-webkit-scrollbar-thumb
  border-radius: 10px
  background: rgba(0, 0, 0, 0.1)
  box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.15)
</style>
<style>
#drag-context-menu {
  display: none;
  position: absolute;
  z-index: 1;
}

#win-context-menu {
  display: none;
  position: absolute;
  z-index: 1;
}

.active-class {
  z-index: 2;
}
</style>
